<template>
	<view class="content">

		<view class="gui-padding">
			<view class="gui-h4 gui-color-black gui-padding">团费缴费</view>

			<view class="gui-padding gui-border-radius-large"
				style="box-shadow: 3rpx 3rpx 3rpx #ccc;border: solid 1rpx #ccc; background-color: rgba(255, 255, 255, 0.6);">
				{{forms.msg}}
			</view>

			<view v-if="show_msg" class="gui-h3 text-center gui-padding gui-border-radius-large gui-margin-top"
				style="box-shadow: 3rpx 3rpx 3rpx #ccc;border: solid 1rpx #ccc; background-color: rgba(255, 255, 255, 0.6);">
				{{msg}}
			</view>

			<view v-if="forms.list.length>0" v-for="(item,index) in forms.list"
				class="gui-padding gui-border-radius-large gui-margin-top"
				style="box-shadow: 3rpx 3rpx 3rpx #ccc;border: solid 1rpx #ccc; background-color: rgba(255, 255, 255, 0.6);">
				<view class="gui-card-body gui-h4 " style="line-height: 2rem;">
					<view>名称: <text style="font-weight: bold; margin-left: 10rpx;">{{item.feenoticeform}}</text></view>
					<view>金额: {{item.feeamount}}</view>
				</view>
			</view>

			<view v-if="forms.status==0 && forms.feeamount>0"
				class="gui-padding gui-text-center gui-border-radius-large gui-margin-top"
				style="box-shadow: 3rpx 3rpx 3rpx #ccc;border: solid 1rpx #ccc; background-color: rgba(255, 255, 255, 0.6);">
				<view class="gui-card-body gui-h4 " style="line-height: 2rem;">
					{{forms.stop_msg}}!
				</view>
			</view>

			<view v-if="forms.status==1 && forms.feeamount>0"
				class="gui-color-black2 gui-border-radius-large gui-margin-top gui-padding"
				style="box-shadow: 3rpx 3rpx 3rpx #ccc;border: solid 1rpx #ccc; background-color: rgba(255, 255, 255, 0.6);">
				<text style="color: rgba(0, 0, 0, 0.8);">请选择支付方式:</text>
				<gui-radio v-if="payTypes.abcBridge" class="pay_type" :checked="payType=='abcBridge'"
					@change="payType='abcBridge'">
					<view class="gui-flex gui-align-items-center" style="gap: 20rpx; margin: 5rpx 0;">
						<image class="pay_icon" src="../../static/pay/new/wjf.png" />微缴费
					</view>
				</gui-radio>
				<gui-radio v-if="payTypes.app" class="pay_type" :checked="payType=='app'" @change="payType='app'">
					<view class="gui-flex gui-align-items-center" style="gap: 20rpx; margin: 5rpx 0;">
						<image class="pay_icon" src="../../static/pay/new/nhzy.png" />农行掌银
					</view>
				</gui-radio>
			</view>

			<view style="width: 90%; margin: 0 auto; margin-top: 60rpx;" v-if="forms.feeamount>0">
				<button type="default" @click="to_pay"
					class="gui-button gui-gtbg-blue gui-box-shadow gui-noborder gui-border-radius-large"
					style="height: 100rpx;">
					<text class="gui-color-white gui-button-text gui-h3" style="line-height: 100rpx">立即缴费</text>
				</button>
			</view>

			<!-- 历史账单查询按钮 -->
			<view class="gui-flex gui-space-between gui-align-items-center gui-padding gui-margin-top">
				<view class="gui-h4 gui-color-black">历史账单查询</view>
				<button type="default" size="mini" class="gui-bg-blue gui-color-white" @click="showHistory = !showHistory">
					{{showHistory ? '隐藏' : '查看'}}历史账单
				</button>
			</view>
			
			<!-- 历史账单查询区域 -->
			<view v-if="showHistory" class="gui-margin-bottom gui-padding gui-border-radius-large"
				style="box-shadow: 3rpx 3rpx 3rpx #ccc;border: solid 1rpx #ccc; background-color: rgba(255, 255, 255, 0.8);">
				<view class="gui-h5 gui-color-black gui-margin-bottom">历史账单查询</view>
				<view class="gui-flex gui-space-between gui-align-items-center gui-margin-bottom">
					<view class="gui-flex gui-align-items-center">
						<text class="gui-color-gray" style="font-size: 25rpx; margin-right: 10rpx;">开始日期:</text>
						<uni-datetime-picker start="2020-01-01" ref="ref_datePicker1" type="date" :clear-icon="false"
							v-model="historyQuery.start_date" @change="changeHistoryDate1" />
					</view>
					<view class="gui-flex gui-align-items-center">
						<text class="gui-color-gray" style="font-size: 25rpx; margin-right: 10rpx">结束日期:</text>
						<uni-datetime-picker ref="ref_datePicker2" type="date" :clear-icon="false"
							v-model="historyQuery.end_date" @change="changeHistoryDate2" />
					</view>
				</view>
				<view class="gui-flex gui-space-between">
					<button type="default" size="mini" class="gui-bg-green gui-color-white" @click="getHistoryData">
						查询历史
					</button>
					<!-- <button type="default" size="mini" class="gui-bg-orange gui-color-white" @click="exportHistory">
						导出记录
					</button> -->
				</view>
				
				<!-- 历史记录显示 -->
				<view v-if="historyList.length > 0" class="gui-margin-top">
					<view class="gui-h5 gui-color-black gui-margin-bottom">团费缴费历史（按时间倒序）</view>
					<view v-for="(item, index) in historyList" :key="'history-'+index"
						class="gui-flex gui-space-between gui-align-items-center gui-border-b gui-padding-small">
						<view style="width: 100rpx;display: flex;align-items: center;justify-content: center;">
							<image :src="getPayIcon(item.pay_type)" style="width: 40rpx;height: 40rpx;" mode="widthFix">
							</image>
						</view>
						<view class="gui-padding-small" style="flex: 1;line-height: 35rpx;">
							<view class="gui-color-black gui-h6">
								{{item.name}}(团费)
							</view>
							<view class="gui-color-gray gui-h6">
								缴费时间: {{item.pay_time}}
							</view>
							<view class="gui-color-blue gui-h6">
								支付方式: {{getPayTypeText(item.pay_type)}}
							</view>
						</view>
						<view class="gui-padding-small" style="width: 140rpx;text-align: right;">
							<view class="gui-color-red gui-h6 gui-bold">
								￥{{item.amount}}
							</view>
							<view class="gui-color-green gui-h6 gui-padding-small gui-border-radius-small status-text">
								缴费成功
							</view>
						</view>
					</view>
				</view>
				<view v-else-if="historySearched && historyList.length === 0" class="gui-text-center gui-color-gray gui-margin-top">
					暂无历史记录
				</view>
			</view>

		</view>
	</view>
</template>

<script>
	var sweixin;
	import menuBar from "./menu_bar"
	export default {
		components: {
			menuBar
		},
		data() {
			return {
				show: false,
				forms: {
					fe_id: 93,
					feenoticeform: '团费',
					feenoticeform_model: {
						start_date: '2024-01-01',
						end_date: '2024-01-31'
					},
					feeamount: null,
					status: 0,
					msg: '团费‌是指中国共产主义青年团团员向团组织交纳的活动经费，是团组织的合法收入。团费的来源主要包括团员交纳的团费、党和政府以及企事业单位关于青少年事业的专项经费、团属经济实体收益、正当的社会资助和团组织的其它合法收入‌',
					stop_msg: '',
					list: []
				},
				fee_item:{},
				payTypes: {
					wx: true,
					app: true,
					abcBridge: true
				},
				payType: null,
				money: 0,
				show_msg: true,
				msg: '查询账单中...',
				payConfig: {
					wx: {
						sysId: "gh_edf4ceb10043",
						appid: "wxcf5c7da8bb74c8af",
						path: "pages/jf/wxpay"
					},
					wx_abc: {
						sysId: "gh_a6986a2f785e",
						appid: "wx78642797f4ce5e50",
						path: "page/containers/payment/query-input/query-input"
					}
				},
				sweixin: '',
				
				// 历史账单查询相关
				showHistory: false,
				historyList: [],
				historySearched: false,
				historyQuery: {
					start_date: '',
					end_date: ''
				}
			}
		},
		onShow() {
			// 初始化历史查询日期
			const today = new Date();
			const year = today.getFullYear();
			const month = today.getMonth() + 1;
			const day = today.getDate();
			this.historyQuery.start_date = `${year}-01-01`;
			this.historyQuery.end_date = `${year}-${String(month).padStart(2, '0')}-${String(day).padStart(2, '0')}`;
			
			this.get_data();
		},
		onLoad() {

		},
		methods: {
			get_data() {
				let self = this;
				this.show_msg=true;
				this.msg="查询账单中...";
				self.forms.list=[];
				self.forms.status=0;
				self.forms.feeamount=0;
				this.$boya.NPost("/app/twjf/query", {
					pay_type: this.payType
				}, function(res) {
					console.log(res);
					if(res.data.list.length==0){
						
						self.msg=res.data.msg || "暂时没有缴费账单"
						return;
					}
					let feeitems=res.data.fee_items;
					self.forms.feeamount = 0;
					self.forms.list = res.data.list;
					self.forms.status = feeitems.status;
					self.forms.feeamount = res.data.sum;
					self.forms.fee_id=feeitems.id;
					if (feeitems.msg != null && feeitems.msg != '') {
						self.forms.msg = feeitems.msg;
					}
					if (feeitems.status == 0) {
						if (feeitems.stop_msg != null && feeitems.stop_msg != '') {
							self.forms.stop_msg = feeitems.stop_msg;
						} else {
							self.forms.stop_msg = "暂停缴费";
						}
					}
					self.fee_item=feeitems;
					self.show_msg = false;
					console.log(self.forms);

				},function(err){
					self.show_msg=false;
					self.msg=err.msg;
				})
			},
			
			// 历史账单查询相关方法
			changeHistoryDate1(e) {
				this.historyQuery.start_date = e;
				this.$refs.ref_datePicker1.close();
			},
			changeHistoryDate2(e) {
				this.historyQuery.end_date = e;
				this.$refs.ref_datePicker2.close();
			},
			getHistoryData() {
				let self = this;
				let parm = {
					"page": 1,
					"limit": 50,
					"type": "tw"
					// 暂时不添加status过滤，看看原始数据
				};
				
				if (this.historyQuery.start_date != '') {
					parm.start_date = this.historyQuery.start_date;
				}
				if (this.historyQuery.end_date != '') {
					parm.end_date = this.historyQuery.end_date;
				}
				
				console.log('查询参数:', parm);
				
				uni.showLoading({
					title: '查询中...'
				});
				
				this.$boya.NGet("/app/pay/order_list", parm, function(res) {
					console.log('团费历史记录: ', res);
					uni.hideLoading();
					self.historySearched = true;
					
					if (res.data && Array.isArray(res.data)) {
						console.log('原始数据长度:', res.data.length);
						console.log('过滤前数据:', res.data);
						
						// 先不过滤状态，看看所有数据
						self.historyList = res.data
							.sort((a, b) => new Date(b.pay_time) - new Date(a.pay_time));
						
						console.log('排序后数据长度:', self.historyList.length);
						console.log('排序后数据:', self.historyList);
						
						// 处理支付状态显示
						self.historyList.forEach(item => {
							item.pay_status_text = self.getPayStatusText(item.pay_status);
							item.pay_type_text = self.getPayTypeText(item.pay_type);
						});
					} else {
						console.log('数据格式不正确:', res.data);
						self.historyList = [];
					}
				}, function(err) {
					console.log('查询历史记录失败:', err);
					uni.hideLoading();
					self.historySearched = true;
					self.historyList = [];
					uni.showToast({
						title: '查询失败',
						icon: 'none'
					});
				});
			},
			exportHistory() {
				if (this.historyList.length === 0) {
					uni.showToast({
						title: '暂无数据可导出',
						icon: 'none'
					});
					return;
				}
				
				// 准备导出数据
				const exportData = this.historyList.map(item => ({
					缴费时间: item.pay_time,
					缴费金额: `￥${item.amount}`,
					支付方式: this.getPayTypeText(item.pay_type),
					缴费状态: '缴费成功'
				}));
				
				// 这里可以调用导出API或生成文件
				console.log('导出数据:', exportData);
				uni.showToast({
					title: '导出功能开发中',
					icon: 'none'
				});
			},
			getPayIcon(payType) {
				switch (payType) {
					case 'wx':
						return '../../static/homePage/wx.png';
					case 'abcBridge':
						return '../../static/homePage/xcx.png';
					case 'OPEN':
						return '../../static/homePage/xcx.png';
					case 'app':
						return '../../static/homePage/nh.png';
					default:
						return '../../static/homePage/wx.png';
				}
			},
			getPayTypeText(payType) {
				switch (payType) {
					case 'wx':
						return '微信支付';
					case 'abcBridge':
						return '微缴费';
					case 'OPEN':
						return '微缴费';
					case 'app':
						return '农行掌银';
					default:
						return '未知方式';
				}
			},
			getPayStatusText(status) {
				switch(Number(status)) {
					case 1:
						return '缴费成功';
					case 0:
						return '处理中';
					case -1:
						return '缴费失败';
					default:
						return '未知状态';
				}
			},
			
			to_pay() {
				let ids = [];
				if (!this.payType) {
					uni.showToast({
						title: "请选择支付类型",
						icon: 'error'
					})
					return;
				}
				for (let i = 0; i < this.forms.list.length; i++) {
					ids.push(this.forms.list[i].id);
				}

				uni.showToast({
					title: "创建订单"
				})
				let self = this;
				let parm = {
					ids: ids.join(","),
					pay_type: this.payType,
					pay_amount: this.forms.feeamount,
					fee_id: this.fee_item.id
				}

				console.log("to_pay->创建订单", JSON.stringify(parm));
				self.loading = true
				this.$boya.NPost("/app/tw/create_order",
					parm,
					function(res) {
						console.log(res);
						uni.showToast({
							title: "发起支付"
						})
						self.loading = false;
						console.log("支付方式：", self.payType);
						let app_id = self.fee_item.app_id
						let app_path = self.fee_item.app_path
						//通过微信小程序支付或微缴费
						res.type = self.payType;
						res.data.type = self.payType;
						res.data.app_id = self.fee_item.app_id;
						res.data.app_path = self.fee_item.app_path;

						if (self.payType == 'abcBridge') {
							//农行微缴费
							res.data.app_id = "gh_a6986a2f785e";
							// res.data.app_path = "page/containers/payment/query-input/query-input?code=" + res.data
							// 	.code;
								
							let user=uni.getStorageSync("userInfo");
							let path = "page/containers/payment/query-input/query-input?code=" + res.data
								.code;							
							path=path+"&userInput="+encodeURIComponent(JSON.stringify({input1:user.id_no,input2:user.real_name}));
							res.data.app_path=path;
						}

						console.log("create_order", JSON.stringify(res));


						uni.navigateTo({
							url: "/pages/pay/pay_info?data=" + encodeURIComponent(JSON.stringify(res)),
							fail(err) {
								console.log(err);
							}
						})

					},
					function(err) {
						console.log("create_order->error", JSON.stringify(err));
						let content = err.msg;
						if (err.data.length > 0) {
							content += ",订单号:" + err.data[0].order_no;
						}
						uni.showModal({
							title: "订单异常",
							content: content,
							showCancel: false

						})
						self.loading = false;
					}
				)

			}
		}
	}
</script>

<style>
	.content {
		width: 100vw;
		height: 100vh;
		background: url('../../static/pay/new/bj1.png') 100% 100% / 100% 100%;
	}

	.synopsis {
		margin: 0 auto;
		border: 5rpx solid black;
		border-radius: 20rpx;

		text-indent: 2em;
		/* 2个字符的宽度 */
		margin-top: 60rpx;
	}

	.pay_type {
		display: flex;
		align-items: center;
		gap: 20rpx;
		font-size: 1.2rem;
		/* border-bottom: 1rpx solid #ccc; */
		padding: 15rpx 10rpx;
		line-height: 50rpx;

		image {
			width: 60rpx;
			height: 60rpx;
			margin-right: 20rpx;
		}

		.gui-radio-lable {
			display: flex;
			align-items: center;
		}
	}

	.pay_icon {
		width: 30px;
		height: 30px;
	}
	
	.status-text {
		white-space: nowrap;
		font-size: 24rpx;
	}
</style>